#!/usr/bin/env python

import SocketServer
from ESL import *

class ESLRequestHandler(SocketServer.BaseRequestHandler ):
	def setup(self):
		print self.client_address, 'connected!'

		fd = self.request.fileno()
		print fd

		con = ESLconnection(fd)
		print "Connected: " 
		print  con.connected()
		if con.connected():

			con.filter("plain", "all")
			info = con.getInfo()

			uuid = info.getHeader("unique-id")
			con.filter("Unique-ID", uuid)
			con.filter("Other-Leg-Unique-ID", uuid)

			con.execute("export", "playback_delimiter=&", uuid)
			con.execute("export", "rtp_timeout_sec=100", uuid)
			con.events("plain", "DTMF_SEND CHANNEL_PROGRESS RING_ASR CHANNEL_PROGRESS_MEDIA CHANNEL_ANSWER CHANNEL_HANGUP CHANNEL_EXECUTE_COMPLETE");
			con.execute("set", "continue_on_fail=true", uuid)
			con.execute("set", "hangup_after_bridge=true", uuid)
			con.execute("set", "park_after_bridge=false", uuid)

			#con.execute("bridge", "sofia/internal/fs20000004@192.168.21.21:8880", uuid)
			con.execute("bridge", "user/1005", uuid)
			con.sendRecv("linger")

			while(con.connected()):
				e = con.recvEvent()
				e_name = e.getHeader('event-name')
				print 'sdfdsf', e_name
				if(e_name == 'CHANNEL_ANSWER'):
					con.execute("export", "rtp_timeout_sec=10", uuid);
				if(e_name == 'CHANNEL_HANGUP'):
					con.disconnect()
					print 'disconnect...'
					break


		
#server host is a tuple ('host', port)
server = SocketServer.ThreadingTCPServer(('', 8899), ESLRequestHandler)
server.serve_forever()


